package com.chockqiu.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

/**
 * 圆形进度条控件
 * @author Administrator
 */
public class CircleProgress extends View {

    private static final String TAG = "CircleProgress";

    private Paint mPaint;
    private RectF mRectF;
    private Rect mRect;
    private int mCurrent = 1, max = 100;
    //圆弧（也可以说是圆环）的宽度
    private float arcWidth = 30;
    //控件的宽度
    private float _width;
    private boolean textShow;

    public CircleProgress(Context context) {
        this(context, null);
    }

    public CircleProgress(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CircleProgress(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mRectF = new RectF();
        mRect = new Rect();
    }

    public void setCurrent(int mCurrent) {
        Log.i(TAG, "当前值：" + mCurrent + "，最大值：" + max);
        this.mCurrent = mCurrent;
        invalidate();
    }

    public void setTextShow(boolean show) {
        textShow = show;
    }

    public void setMax(int max) {
        this.max = max;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //getMeasuredWidth获取的是view的原始大小，也就是xml中配置或者代码中设置的大小
        //getWidth获取的是view最终显示的大小，这个大小不一定等于原始大小
        _width = getMeasuredWidth();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //绘制圆形
        //设置为空心圆，如果不理解绘制弧线是什么意思就把这里的属性改为“填充”，跑一下瞬间就明白了
        mPaint.setStyle(Paint.Style.STROKE);
        //设置圆弧的宽度（圆环的宽度）
        mPaint.setStrokeWidth(arcWidth);
        mPaint.setColor(Color.GRAY);
        //大圆的半径
        float bigCircleRadius = _width / 2;
        //小圆的半径
        float smallCircleRadius = bigCircleRadius - arcWidth;
        //绘制小圆
        canvas.drawCircle(bigCircleRadius, bigCircleRadius, smallCircleRadius, mPaint);
        mPaint.setColor(Color.RED);
        mRectF.set(arcWidth, arcWidth, _width - arcWidth, _width - arcWidth);
        //绘制圆弧
        canvas.drawArc(mRectF, 90, mCurrent * 360 / max, false, mPaint);
        if (textShow) {
            //计算百分比
            String txt = mCurrent * 100 / max + "%";
            mPaint.setStrokeWidth(0);
            mPaint.setTextSize(40);
            mPaint.getTextBounds(txt, 0, txt.length(), mRect);
            mPaint.setColor(Color.RED);
            //绘制百分比
            canvas.drawText(txt, bigCircleRadius - mRect.width() / 2, bigCircleRadius + mRect.height() / 2, mPaint);
        }
    }

}